package org.hxyjs.dao.impl;

import org.hxyjs.dao.OrderFormDao;
import org.hxyjs.entity.OrderForm;
import org.hxyjs.mapper.OrderFormMapper;
import org.hxyjs.page.PageInfo;
import org.hxyjs.utils.GenNumTools;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Repository("orderFormDao")//一般实现类不会直接生成默认对象名 而是使用 接口的默认对象名
public class OrderFormDaoImpl implements OrderFormDao {
    @Resource //autowired 会装配能够直接扫描到的对象  resource spring容器运行的时候才找到需要的对象  注入
    private OrderFormMapper orderFormMapper;

    public List<OrderForm>  getAllOrderForms() throws Exception{
        return orderFormMapper.selectByExample(null);
    }
    public List<OrderForm> getOrderFormByPage(PageInfo pageInfo) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("currPage",pageInfo.getCurrPage());
        map.put("pageSize",pageInfo.getPageSize());
        int itemCount =(int) orderFormMapper.countByExample(null);
        pageInfo.setItemCount(itemCount);
        return orderFormMapper.getOrderFormByPage(map);
    }

//    @Override
//    public OrderForm selectOrderFormByUrno(String sno) throws Exception {
//        return orderFormMapper.selectByPrimaryKey(sno);
//    }


    @Override
    public Integer deleteOrderFormByUrno(String urno) {
        return orderFormMapper.deleteByPrimaryKey(urno);
    }

    @Override
    public Integer updateOrderFormByUrno(OrderForm orderForm) {
        return orderFormMapper.updateByPrimaryKey(orderForm);
    }

    @Override
    public Integer addOrderForm(OrderForm orderForm) {
        orderForm.setUrno(initId(orderForm.getUno() + orderForm.getRno()));
        return orderFormMapper.insertSelective(orderForm);
    }


    public String initId(String urnobegin) {
        String maxUrno = orderFormMapper.getMaxUrno(urnobegin);
        System.out.println("-----222");
        System.out.println(maxUrno);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
        String timeStr = df.format(new Date());
        System.out.println(timeStr);
         String   newUrno= Optional.ofNullable(maxUrno).isPresent()?GenNumTools.initId( urnobegin+timeStr, 1, maxUrno):urnobegin +timeStr+"1";//如果数据库查到最大的主键则处理后生成新的主键否则就生成编号为一的主键
        return newUrno;

    }
    @Override
    public OrderForm getOrderFormByUrno(String urno) throws Exception{
        return orderFormMapper.selectByPrimaryKey(urno);
    }

}